#encoding=utf8

_pinyin_mapping = None

def load():
  """加载拼音字典"""
  global _pinyin_mapping
  if _pinyin_mapping != None: return
  _pinyin_mapping = {}
  fin = open("pinyin.txt", "r")
  for line in fin.readlines():
    line = line.strip()
    if line == "": continue
    if type(line) == str:
      line = unicode(line, "utf8")
    i = line.find("=")
    if i > 0:
      _pinyin_mapping[line[:i]] = line[i+1:]

      
def convert():
  _pinyin_mapping = {}
  fin = open("pinyin.txt", "r")
  for line in fin.readlines():
    line = line.strip()
    if line == "": continue
    i = line.find("=")
    if i > 0:
      if _pinyin_mapping.has_key(line[:i]):
        _pinyin_mapping[line[:i]].append(line[i+1:])
      else:
        _pinyin_mapping[line[:i]] = [line[i+1:]]
  fin.close()

  fin = open("pinyin.txt", "r")
  fout = open("pinyin.js", "w")
  for line in fin.readlines():
    line = line.strip()
    if line == "": continue
    i = line.find("=")
    if i > 0:
      key = line[:i]
      if not _pinyin_mapping.has_key(key): continue
      fout.write("'%s':'" % key)
      s = False
      for p in _pinyin_mapping[key]:
        if s: fout.write(",")
	else: s = True
        fout.write(p)
      fout.write("',")
      del _pinyin_mapping[key]
  fin.close()

def toPinYin(txt):
  """将中文转化为拼音"""
  if type(txt) == str:
    txt = unicode(txt, "utf8")
  load()
  result = ""
  for ch in txt:
    if _pinyin_mapping.has_key(ch): result += _pinyin_mapping[ch]
    else: result += ch
  return result.encode("utf8")

def toPinShou(txt):
  """将中文转化为拼首"""
  if type(txt) == str:
    txt = unicode(txt, "utf8")
  load()
  result = ""
  for ch in txt:
    if _pinyin_mapping.has_key(ch): result += _pinyin_mapping[ch][:1]
    else: result += ch
  return result.encode("utf8")

if __name__ == "__main__":
  print toPinYin("china")
  print toPinYin(u"中国")
  print toPinShou("中国")
  convert()